package com.mvvmhabit.org.custom.load

import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.WindowManager
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import androidx.fragment.app.FragmentActivity
import com.mvvmhabit.org.BR
import com.mvvmhabit.org.R
import com.mvvmhabit.org.base.BaseDialog
import com.mvvmhabit.org.databinding.DialogLoadBinding
import com.mvvmhabit.org.utils.ScreenUtil

// 数据加载展示Dialog
class LoadDialog private constructor(context: FragmentActivity, val title: String?) :
    BaseDialog<DialogLoadBinding, LoadViewModel>(context) {

    override fun layoutId(savedInstanceState: Bundle?): Int = R.layout.dialog_load

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun initViewModel(): Class<LoadViewModel> = LoadViewModel::class.java

    override fun initData() {
        if (!TextUtils.isEmpty(title)) {
            mBinding.message.text = title
        }
        val rotateAnimation = AnimationUtils.loadAnimation(context, R.anim.ratate_anim)
        val lin = LinearInterpolator()
        rotateAnimation.interpolator = lin
        mBinding.ivLoad.startAnimation(rotateAnimation)
        if (window != null) {
            window!!.clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND)
            val lp = window!!.attributes
            lp.width = ScreenUtil.dp2px(context, 180F)
            lp.height = ScreenUtil.dp2px(context, 180F)
            window!!.setGravity(Gravity.CENTER)
            window!!.attributes = lp
        } else {
            println("展示对话框前先消失")
            dismiss()
        }
    }

    companion object {
        private var loadingDialog: LoadDialog? = null

        fun show(activity: FragmentActivity, title: String?) {
            synchronized(LoadDialog::class.java) {
                try {
                    if (loadingDialog == null) {
                        loadingDialog = LoadDialog(activity, title)
                    }
                    loadingDialog!!.show()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }

        fun dismiss() {
            try {
                if (loadingDialog != null && loadingDialog!!.isShowing) {
                    loadingDialog!!.dismiss()
                    loadingDialog = null
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun destroy() {
            loadingDialog?.onDestroy()
        }
    }

}